<template>
  <div class="login-container flex-center">
    <el-form ref="loginForm" :model="loginForm" :rules="loginRules" class="login-form" label-position="left">
      <el-row class="flex-center">
        <img class="login-form-img" src="~@/assets/login_images/login-title.jpg"/>
      </el-row>
      <el-row class="flex-center">
        <span class="login-form-title">情绪识别系统</span>
      </el-row>
      <el-row class="flex-center" style="height:0.9rem;">
        <el-form-item prop="username" style="margin-top: 0.3rem">
          <el-input
            ref="username"
            v-model="loginForm.username"
            placeholder="请输入用户名"
            name="username"
            type="text"
          />
        </el-form-item>
      </el-row>
      <el-row class="flex-center" style="height:0.76rem;">
        <el-form-item prop="password" style="margin-top: 0.08rem;">
          <el-input
            ref="password"
            v-model="loginForm.password"
            :type="passwordType"
            placeholder="请输入密码"
            name="password"
            @keyup.enter.native="handleLogin"
          />
          <span class="show-pwd" @click="showPwd">
            <i class="el-icon-view"></i>
          </span>
        </el-form-item>
      </el-row>
      <el-row class="flex-center" style="height:0.49rem;">
        <el-button class="login-form-btn" :loading="loading" type="primary" @keydown.enter="handleLogin" @click.native.prevent="handleLogin">登 录</el-button>
      </el-row>
    </el-form>
  </div>
</template>

<script>

export default {
  name: 'Login',
  data() {
    return {
      loginForm: {
        username: 'admin',
        password: '111111'
      },
      loginRules: {
        username: [{ required: true, trigger: 'blur' }],
        password: [{ required: true, trigger: 'blur' }]
      },
      loading: false,
      passwordType: 'password',
      redirect: undefined
    }
  },
  watch: {
    $route: {
      handler: function(route) {
        this.redirect = route.query && route.query.redirect
      },
      immediate: true
    }
  },
  methods: {
    showPwd() {
      if (this.passwordType === 'password') {
        this.passwordType = ''
      } else {
        this.passwordType = 'password'
      }
      this.$nextTick(() => {
        this.$refs.password.focus()
      })
    },
    handleLogin() {
      this.$refs.loginForm.validate(valid => {
        if (valid) {
          this.loading = true
          this.$store.dispatch('user/login', this.loginForm).then(() => {
            this.$router.push({ path: this.redirect || '/' })
            this.loading = false
          }).catch(() => {
            this.loading = false
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    }
  }
}
</script>

<style lang="scss">
@import "./styles/index.scss";
</style>

